<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\logic\OrderLogic;
use app\common\model\AgentWithdrawalRecord;
use app\common\model\Coupon;
use app\common\model\CouponSetting;
use app\common\model\Member;
use app\common\model\MoneyRecord;
use app\common\model\Order;
use app\common\model\ServiceTimes;
use app\job\CancelOrder;
use EasyWeChat\Factory;
use think\Db;
use think\Exception;
use think\Queue;
use think\Request;

class Crontab extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    public $OrderLogic;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->OrderLogic = new OrderLogic();
    }

    /**
     * 定时删除未支付的订单
     */
    public function cancel_order()
    {
        $time = time()-7200;//自动取消2小时前未支付的订单
        Order::update(['cancel_time'=>time(),'order_status'=>Order::ORDER_STATUS_CANCEL],['order_status'=>Order::ORDER_STATUS_WAIT_PAY,'createtime'=>['lt',$time]]);
        exit();
    }

    /**
     * 定时查询已转账的微信提现
     */
    public function wx_pay()
    {
        $list = AgentWithdrawalRecord::where(['status'=>4,'method'=>2])->select()->toArray();
        if (!empty($list)){
            foreach ($list as $v){
                Queue::push(\app\job\WxPay::class,['id'=>$v['id'],],'message');
            }
        }
        exit();
    }

    /**
     * 定时查询已转账的用户端微信提现
     */
    public function member_wx_pay()
    {
        $list = MoneyRecord::where(['type'=>2,'detail_type'=>2,'tx_status'=>1])->select()->toArray();
        if (!empty($list)){
            foreach ($list as $v){
                Queue::push(\app\job\MemberWxPay::class,['id'=>$v['id'],],'message');
            }
        }
        exit();
    }

    /**
     * 定时取消vip
     */
    public function cancel_vip()
    {
        $list = ServiceTimes::where(['is_vip'=>1,'end_time'=>['lt',time()]])->select()->toArray();
        if (!empty($list)){
            foreach ($list as $v){
                ServiceTimes::update(['is_vip'=>0],['id'=>$v['id']]);
                Member::update(['is_vip'=>0],['id'=>$v['member_id']]);
            }
        }
        exit();
    }

    /**
     * 超时未核销入队列取消
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cancel_not_audit_order()
    {
        $list = Order::where(['order_status'=>Order::ORDER_STATUS_WAIT_AUDIT,'expires_time'=>['lt',time()]])->select()->toArray();
        foreach ($list as $v){
            Queue::push(CancelOrder::class,$v,'message');
        }
        exit('超时未核销入队列取消获取完毕');


//        // 当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
//        $jobHandlerClassName = "app\message\controller\Order@cancel_not_audit_order";
//        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
//        $jobQueueName = "cancel_not_audit_order";
//        $list = Order::where(['order_status'=>Order::ORDER_STATUS_WAIT_AUDIT,'expires_time'=>['lt',time()]])->select()->toArray();
//        foreach ($list as $v){
//            Queue::push($jobHandlerClassName,$v,$jobQueueName);
//        }
//        exit();
    }



    public function sendBirthdayCoupon()
    {
        try{
            $start_time = strtotime(date('Y-m-01 00:00:00'));//本月起始时间戳
            $end_time  = strtotime(date('Y-m-t 23:59:59'));//本月结束时间戳
            $ids = CouponSetting::where('rule',2)->column('id');
            if (empty($ids))
                exit('无生日券可发放');
            $list = Member::whereRaw("MONTH (FROM_UNIXTIME ( birthday )) = 8")->select();
            foreach ($list as $v){
                //查询本月是否已经赠送过了
                $res = Coupon::where(['member_id'=>$v['id'],'setting_id'=>['in',$ids],'createtime'=>['between',[$start_time,$end_time]]])->find();//查询本月是否已经发放过生日券
                if ($res)
                    continue;
                $coupon_info = CouponSetting::where(['rule'=>2,'status'=>1,'get_begin_time'=>['lt',time()],'get_end_time'=>['gt',time()]])->find();
                if (empty($coupon_info))
                    continue;
                if ($coupon_info['date_type'] == 1){
                    $begin_time = strtotime($coupon_info['use_begin_time']);
                    $end_time = strtotime($coupon_info['use_end_time']);
                }elseif ($coupon_info['date_type'] == 2){
                    $begin_time = time();
                    if ($coupon_info['fixed_day'] == 1){
                        $end_time = strtotime(date("Y-m-d 23:59:59"));
                    }else{
                        $days = $coupon_info['fixed_day'] -1;
                        $end_time = strtotime(date("Y-m-d 23:59:59",strtotime("+".$days." day")));
                    }
                }
                Coupon::create(['member_id'=>$v['id'], 'money'=>$coupon_info['money'], 'type'=>$coupon_info['type'], 'least_cost'=>$coupon_info['least_cost'], 'begin_time'=>$begin_time, 'end_time'=>$end_time, 'setting_id'=>$coupon_info['id'], 'status'=>1]);
            }
            exit('发送本月生日券执行成功');
        }catch (Exception $e){
            exit('发送本月生日券执行失败：'.$e->getMessage());
        }

    }

}
